import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 修复路由重复错误：NavigationDuplicated: Avoided redundant navigation to current location: “/“
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

import Layout from '@/layout'

/**
 * 常量路由
 * hidden：设置了hidden:true，则当前路由不在左侧菜单显示
 * alwaysShow：children为1级的时候，默认是不显示上级路由的，如果想显示。就设置alwaysShow:true,在上级路由里面
 * affix：固定路由到标签栏中
 * isCache：跳转菜单，是否要缓存路由
 */
const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home'),
        meta: { title: '首页', affix: true }
      }
    ]
  },
  {
    path: '/user',
    component: Layout,
    children: [
      {
        path: 'index',
        name: 'User',
        component: () => import('@/views/user'),
        meta: { title: '用户', isCache: true }
      }
    ]
  },
  {
    path: '/test',
    component: Layout,
    meta: {title: '测试'},
    children: [
      {
        path: 'test-mock',
        name: 'test-mock',
        component: () => import('@/views/test/test-mock.vue'),
        meta: { title: '测试模拟接口', isCache: true }
      },
      {
        path: 'test2',
        name: 'test2',
        component: () => import('@/views/test/test2.vue'),
        meta: { title: '测试22', isCache: true }
      }
    ]
  }
]

const createRouter = () => new Router({
  routes: constantRoutes,
  scrollBehavior: () => ({ y: 0 })
})

const router = createRouter()

// 重置路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // the relevant part
}

export default router
